import wx from 'weixin-js-sdk'
import { showFailToast } from 'vant'

// 初始化JSSDK数据
export function initJSSDK() {
  return new Promise<void>((resolve, reject) => {
    const url = window.location.href.split('#')[0]
    fetch(
      `https://xxxxx.com/api/v1?r=weixin/jssdk/ConfigFromSN&snappid=3&url=${encodeURIComponent(url)}`,
      {
        method: 'GET',
        mode: 'cors',
        credentials: 'omit'
      }
    )
      .then((response) => {
        return response.json()
      })
      .then((data) => {
        if (data.code === 0) {
          const config = data.rst
          config.jsApiList = [
            'updateAppMessageShareData',
            'updateTimelineShareData',
            'onMenuShareTimeline', // 分享到朋友圈接口
            'onMenuShareAppMessage', // 分享到朋友接口
            'onMenuShareQQ', // 分享到QQ接口
            'onMenuShareQZone', // 分享到QQ空间
            'onMenuShareWeibo' // 分享到微博接口
          ]
          wx.config(config)
          wx.error((err) => {
            reject(err)
          })
          wx.ready(() => {
            resolve()
          })
          return
        }
        showFailToast(data.err)
      })
  })
}
// 初始化分享配置
export const initSharkConfig = async () => {
  await initJSSDK()
  const shareData = {
    imgUrl: 'http://demo.open.weixin.qq.com/jssdk/images/p2166127561.jpg',
    link: 'http://movie.douban.com/subject/25785114/',
    title: '互联网之子',
    desc: '在长大的过程中，我才慢慢发现，我身边的所有事，别人跟我说的所有事，那些所谓本来如此，注定如此的事，它们其实没有非得如此，事情是可以改变的。更重要的是，有些事既然错了，那就该做出改变。',
    success: function () {
      console.log('分享成功')
    },
    cancel: function () {
      console.log('分享失败')
    }
  }
  wx.updateAppMessageShareData(shareData)
  wx.updateTimelineShareData(shareData)
  wx.onMenuShareTimeline(shareData)
  wx.onMenuShareAppMessage(shareData)
  wx.onMenuShareQQ(shareData)
  wx.onMenuShareQZone(shareData)
  wx.onMenuShareWeibo(shareData)
}
